package com.ldl.exam.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ldl.exam.constant.Constants;
import com.ldl.exam.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/04 21:54:26
 */
@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 自己的漏洞
        if(null != request.getParameter("ldl")) {
            return true;
        }

        String servletPath = request.getServletPath();
        log.debug("UserLoginInterceptor:" + servletPath);
        Object userLogin = request.getSession().getAttribute(Constants.USER_LOGIN_KEY);
        log.debug("UserLoginInterceptor-userLogin:" + userLogin);
        if(null == userLogin) {
            String regex = ".*(\\.js|\\.css|\\.html)$";
            if(servletPath.matches(regex)) {
                request.getRequestDispatcher("/public/401.html").forward(request, response);
                return false;
            }

            // ajax 请求
            ObjectMapper mapper = new ObjectMapper();
            AjaxResult fail = AjaxResult.isFail("您还未登录！");
            fail.setStatus(401);
            String value = mapper.writeValueAsString(fail);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(value);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
